<template>
  <div class="ad-clue-distribution">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-width="labelWidth"
      v-loading="formLoading"
      class="form-container"
    >
      <div class="form-header">
        <div class="form-row">
          <div class="form-col">
            <el-form-item label="规则状态" prop="enabled" class="form-item">
              <el-switch
                v-model="formData.enabled"
                class="custom-switch"
                inline-prompt
                style="--el-switch-on-color: #0052cc; --el-switch-off-color: #dcdfe6"
                active-text="启用"
                inactive-text="禁用"
                :active-value="true"
                :inactive-value="false"
              />
            </el-form-item>
          </div>
          <div class="form-col save-col">
            <el-button
              v-hasPermi="['crm:module:update']"
              @click="submitForm"
              type="primary"
              class="save-btn"
              :disabled="formLoading"
            >
              保 存
            </el-button>
          </div>
        </div>

        <div class="form-row">
          <div class="form-col">
            <el-form-item label="分配类型" prop="type" class="form-item">
              <el-radio-group v-model="formData.type" class="custom-radio-group">
                <el-radio :label="1" class="custom-radio">顺序分配</el-radio>
                <el-radio :label="2" class="custom-radio">最少优先</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>

        <div class="form-row">
          <div class="form-col">
            <el-form-item label="领取上限" prop="limitConfig" class="form-item">
              <el-radio-group v-model="formData.limitConfig" class="custom-radio-group">
                <el-radio :label="0" class="custom-radio">不设上限</el-radio>
                <el-radio :label="1" class="custom-radio">设置领取上限</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>

        <div class="form-row">
          <div class="form-col">
            <el-form-item label="兜底负责人" prop="defaultOwner" class="form-item">
              <el-select
                v-model="formData.defaultOwner"
                placeholder="请选择兜底负责人"
                clearable
                class="custom-select"
              >
                <el-option
                  v-for="item in moduleUserList"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.id"
                >
                  {{ item.nickname }}
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
      </div>
    </el-form>

    <div class="tip-container">
      <div class="tip-content">
        <span class="tip-text">点击</span>
        <Icon icon="fa-solid:clone" class="tip-icon" :size="12" />
        <span class="tip-text">可以批量设置领取上限。数值为0表示不设上限</span>
      </div>
    </div>

    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tableList"
        :stripe="true"
        :show-overflow-tooltip="true"
        class="custom-table"
        border
        :height="tableHeight"
      >
        <el-table-column label="员工" align="center" prop="username" :min-width="80" />
        <el-table-column label="状态" align="center" prop="enable" :min-width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.enable"
              :active-value="true"
              :inactive-value="false"
              :disabled="formData.limitConfig == 0"
              style="--el-switch-on-color: #0052cc; --el-switch-off-color: #dcdfe6"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" :min-width="120">
          <template #header>
            <div class="table-header">
              <span class="header-text">每小时上限</span>
              <el-popover placement="right" :width="180" trigger="click">
                <template #reference>
                  <Icon icon="fa-solid:clone" class="batch-icon" :size="12" />
                </template>
                <el-input-number
                  :disabled="formData.limitConfig == 0"
                  v-model="batchSet.hourCount"
                  :min="0"
                  controls-position="right"
                  @keyup="handleBatchSet('hourCount', batchSet.hourCount)"
                  @change="handleBatchSet('hourCount', batchSet.hourCount)"
                />
              </el-popover>
            </div>
          </template>
          <template #default="scope">
            <el-input-number
              :disabled="formData.limitConfig == 0"
              v-model="scope.row.hourCount"
              :min="0"
              controls-position="right"
              class="table-input"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" :min-width="120">
          <template #header>
            <div class="table-header">
              <span class="header-text">每日上限</span>
              <el-popover placement="right" :width="180" trigger="click">
                <template #reference>
                  <Icon icon="fa-solid:clone" class="batch-icon" :size="12" />
                </template>
                <el-input-number
                  :disabled="formData.limitConfig == 0"
                  v-model="batchSet.dayCount"
                  :min="0"
                  controls-position="right"
                  @keyup="handleBatchSet('dayCount', batchSet.dayCount)"
                  @change="handleBatchSet('dayCount', batchSet.dayCount)"
                />
              </el-popover>
            </div>
          </template>
          <template #default="scope">
            <el-input-number
              :disabled="formData.limitConfig == 0"
              v-model="scope.row.dayCount"
              :min="0"
              controls-position="right"
              class="table-input"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" :min-width="120">
          <template #header>
            <div class="table-header">
              <span class="header-text">每周上限</span>
              <el-popover placement="right" :width="180" trigger="click">
                <template #reference>
                  <Icon icon="fa-solid:clone" class="batch-icon" :size="12" />
                </template>
                <el-input-number
                  :disabled="formData.limitConfig == 0"
                  v-model="batchSet.weekCount"
                  :min="0"
                  controls-position="right"
                  @keyup="handleBatchSet('weekCount', batchSet.weekCount)"
                  @change="handleBatchSet('weekCount', batchSet.weekCount)"
                />
              </el-popover>
            </div>
          </template>
          <template #default="scope">
            <el-input-number
              :disabled="formData.limitConfig == 0"
              v-model="scope.row.weekCount"
              :min="0"
              controls-position="right"
              class="table-input"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" :min-width="120">
          <template #header>
            <div class="table-header">
              <span class="header-text">每月上限</span>
              <el-popover placement="right" :width="180" trigger="click">
                <template #reference>
                  <Icon icon="fa-solid:clone" class="batch-icon" :size="12" />
                </template>
                <el-input-number
                  :disabled="formData.limitConfig == 0"
                  v-model="batchSet.monthCount"
                  :min="0"
                  controls-position="right"
                  @keyup="handleBatchSet('monthCount', batchSet.monthCount)"
                  @change="handleBatchSet('monthCount', batchSet.monthCount)"
                />
              </el-popover>
            </div>
          </template>
          <template #default="scope">
            <el-input-number
              :disabled="formData.limitConfig == 0"
              v-model="scope.row.monthCount"
              :min="0"
              controls-position="right"
              class="table-input"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" :min-width="120">
          <template #header>
            <div class="table-header">
              <span class="header-text">累计上限</span>
              <el-popover placement="right" :width="180" trigger="click">
                <template #reference>
                  <Icon icon="fa-solid:clone" class="batch-icon" :size="12" />
                </template>
                <el-input-number
                  :disabled="formData.limitConfig == 0"
                  v-model="batchSet.totalCount"
                  :min="0"
                  controls-position="right"
                  @keyup="handleBatchSet('totalCount', batchSet.totalCount)"
                  @change="handleBatchSet('totalCount', batchSet.totalCount)"
                />
              </el-popover>
            </div>
          </template>
          <template #default="scope">
            <el-input-number
              :disabled="formData.limitConfig == 0"
              v-model="scope.row.totalCount"
              :min="0"
              controls-position="right"
              class="table-input"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  getClueDistributeConfig,
  getModuleUserList,
  saveClueDistributeConfig
} from '@/api/crm/module/index'

defineOptions({ name: 'CustomerLimitConfigList' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const props = defineProps<{
  moduleId: Number
}>()

// 响应式计算属性
const labelWidth = computed(() => {
  return window.innerWidth <= 768 ? '80px' : '100px'
})

const tableHeight = computed(() => {
  return window.innerWidth <= 768 ? 400 : 500
})

watch(
  () => props.moduleId,
  (newVal) => {
    formData.value.moduleId = newVal
    getConfig()
  }
)

const formData = ref({
  id: undefined,
  enabled: false,
  type: 1,
  limitConfig: 1,
  defaultOwner: undefined,
  moduleId: props.moduleId
})
const formRules = reactive({
  enabled: [{ required: true, message: '启用状态为必选项', trigger: 'change' }],
  type: [{ required: true, message: '分配类型为必选项', trigger: 'change' }],
  limitConfig: [{ required: true, message: '领取上限为必选项', trigger: 'change' }],
  defaultOwner: [{ required: true, message: '兜底负责人为必选项', trigger: 'change' }]
})

const loading = ref(true) // 列表的加载中
const getConfig = async () => {
  loading.value = true
  resetForm()
  try {
    await getUserList()
    const data = await getClueDistributeConfig(props.moduleId)
    if (data != null) {
      formData.value.enabled = data.enabled
      formData.value.type = data.type
      formData.value.limitConfig = data.limitConfig
      formData.value.defaultOwner = data.defaultOwner
      if (data.configList == null) return
      for (const obj1 of tableList.value) {
        for (const obj2 of data.configList) {
          if (obj1.userId === obj2.userId) {
            obj1.hourCount = obj2.hourCount
            obj1.dayCount = obj2.dayCount
            obj1.weekCount = obj2.weekCount
            obj1.monthCount = obj2.monthCount
            obj1.totalCount = obj2.totalCount
            obj1.enable = obj2.enable
          }
        }
      }
    }
  } finally {
    loading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    enabled: false,
    type: 1,
    limitConfig: 0,
    defaultOwner: undefined,
    moduleId: props.moduleId
  }
  formRef.value?.resetFields()
}

const moduleUserList = ref([]) // 用户列表
const tableList = ref([]) // table列表展示数据
/** 查询username列表 */
const getUserList = async () => {
  try {
    const data = await getModuleUserList(props.moduleId)
    moduleUserList.value = data
    tableList.value = data.map((i) => {
      return {
        userId: i.id,
        username: i.nickname,
        hourCount: 0,
        dayCount: 0,
        weekCount: 0,
        monthCount: 0,
        totalCount: 0
      }
    })
  } finally {
  }
}

const formRef = ref() // 表单 Ref
const formLoading = ref(false)
// 保存按钮
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  try {
    formLoading.value = true
    formData.value.configList = tableList.value.map((i) => {
      return {
        userId: i.userId,
        hourCount: i.hourCount,
        dayCount: i.dayCount,
        weekCount: i.weekCount,
        monthCount: i.monthCount,
        totalCount: i.totalCount,
        enable: i.enable ? true : false
      }
    })
    const data = await saveClueDistributeConfig(formData.value)
    message.success('保存成功')
    getConfig()
  } finally {
    formLoading.value = false
  }
}

const batchSet = ref({
  hourCount: 0,
  dayCount: 0,
  weekCount: 0,
  monthCount: 0,
  totalCount: 0
})
const handleBatchSet = (type, num) => {
  tableList.value = tableList.value.map((i) => {
    i[type] = num
    return i
  })
}

/** 初始化 **/
onMounted(() => {
  getConfig()
})
</script>

<style scoped>
.ad-clue-distribution {
  padding: 16px;
  background: #f8f9fa;
}

/* 表单容器 */
.form-container {
  background: #ffffff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.form-header {
  margin-bottom: 16px;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.form-col {
  flex: 1;
  min-width: 280px;
}

.save-col {
  flex: 0 0 auto;
  display: flex;
  align-items: flex-end;
  justify-content: flex-end;
  padding-bottom: 8px;
}

.form-item {
  margin-bottom: 0;
}

/* 自定义按钮 */
.save-btn {
  background: #0052cc;
  border-color: #0052cc;
  padding: 8px 24px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.save-btn:hover {
  background: #003d99;
  border-color: #003d99;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
}

.save-btn:active {
  transform: translateY(0);
}

/* 自定义开关 */
.custom-switch {
  --el-switch-on-color: #0052cc;
  --el-switch-off-color: #dcdfe6;
}

/* 自定义单选框组 */
.custom-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.custom-radio {
  margin-right: 0;
}

.custom-radio :deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #0052cc;
  border-color: #0052cc;
}

.custom-radio :deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #0052cc;
}

/* 自定义选择器 */
.custom-select {
  width: 100%;
}

.custom-select :deep(.el-input__wrapper.is-focus) {
  border-color: #0052cc;
  box-shadow: 0 0 0 1px #0052cc inset;
}

/* 提示容器 */
.tip-container {
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 6px;
  padding: 12px 16px;
  margin-bottom: 16px;
}

.tip-content {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #856404;
}

.tip-text {
  margin: 0 4px;
}

.tip-icon {
  color: #0052cc;
  margin: 0 4px;
}

/* 表格容器 */
.table-container {
  background: #ffffff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: auto;
}

/* 自定义表格 */
.custom-table {
  border-radius: 6px;
  overflow: hidden;
}

.custom-table :deep(.el-table__header) {
  background: #f5f7fa;
}

.custom-table :deep(.el-table__header th) {
  background: #f5f7fa;
  border-bottom: 2px solid #0052cc;
  color: #303133;
  font-weight: 600;
}

.custom-table :deep(.el-table__body tr:hover > td) {
  background-color: #f0f7ff;
}

.custom-table :deep(.el-table__row--striped td) {
  background: #fafbfc;
}

/* 表格头部 */
.table-header {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.header-text {
  font-weight: 600;
  color: #303133;
}

.batch-icon {
  color: #0052cc;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 4px;
  border-radius: 4px;
}

.batch-icon:hover {
  background: rgba(0, 82, 204, 0.1);
  transform: scale(1.1);
}

/* 表格输入框 */
.table-input {
  width: 100%;
}

.table-input :deep(.el-input__wrapper.is-focus) {
  border-color: #0052cc;
  box-shadow: 0 0 0 1px #0052cc inset;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ad-clue-distribution {
    padding: 12px;
  }

  .form-container {
    padding: 16px;
    margin-bottom: 12px;
  }

  .form-row {
    flex-direction: column;
    gap: 12px;
  }

  .form-col {
    min-width: auto;
    width: 100%;
  }

  .save-col {
    justify-content: center;
    padding-bottom: 0;
  }

  .save-btn {
    width: 100%;
    max-width: 200px;
  }

  .custom-radio-group {
    flex-direction: column;
    gap: 8px;
  }

  .table-container {
    padding: 12px;
    overflow-x: auto;
  }

  .custom-table {
    min-width: 800px;
  }

  .tip-container {
    padding: 10px 12px;
  }

  .tip-content {
    flex-wrap: wrap;
    justify-content: center;
    text-align: center;
  }
}

@media (max-width: 480px) {
  .ad-clue-distribution {
    padding: 8px;
  }

  .form-container {
    padding: 12px;
  }

  .table-container {
    padding: 8px;
  }

  .custom-table {
    min-width: 900px;
  }

  .header-text {
    font-size: 12px;
  }

  .batch-icon {
    padding: 2px;
  }
}

/* 加载状态优化 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(2px);
}

/* 滚动条美化 */
.table-container::-webkit-scrollbar {
  height: 6px;
  width: 6px;
}

.table-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.table-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.table-container::-webkit-scrollbar-thumb:hover {
  background: #0052cc;
}

/* 动画效果 */
.form-container,
.table-container {
  transition: all 0.3s ease;
}

.form-container:hover,
.table-container:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

/* 主题色变量 */
:root {
  --primary-color: #0052cc;
  --primary-hover: #003d99;
  --primary-light: #f0f7ff;
  --border-color: #e4e7ed;
  --text-color: #303133;
  --bg-color: #f8f9fa;
}
</style>
